import type {MetaField, MetaView} from "../../../types/tool/meta.types";
import type {DataItem} from "../../../types/tool/dao.types";
import {computed, type Ref} from "vue";

export default function useDTableCell(view: Ref<MetaView>) {

    const mapping = computed<{
        [key: string]: MetaField;
    }>(() => {
        return view.value.fields || {}
    })

    function getValue(prop: string, row: DataItem) {
        const field = mapping.value[prop] || {}
        const domain = field.domain as string;
        switch (domain) {
            case 'ForeignKey':
            case 'OneToOneField':
            case 'OneToOneRel':
                const _prop = prop.replace('_id', '')
                const _label = field.refer?.label || 'name'
                return (row[_prop] || {})[_label]
            case 'ManyToOneRel':
            case 'ManyToManyRel':
            case 'ManyToManyField':
                const $prop = `${prop}_set`
                const $label = field.refer?.label || 'name'
                return row[$prop]?.map((e: any) => e[$label]).join(', ')
            default:
                return row[prop]
        }
    }

    return {getValue}
}